package xyz.zhouxf.rpc.provider.impl;

import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import xyz.zhouxf.rpc.enumeration.RpcError;
import xyz.zhouxf.rpc.exception.RpcException;
import xyz.zhouxf.rpc.provider.ServiceProvider;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhouxf
 * @date 2022/8/31
 */
public class DefaultServiceProvider implements ServiceProvider {

    private static final Map<String, Object> serviceMap;
    private static final Set<String> registeredService;

    static {
        serviceMap = new ConcurrentHashMap<>();
        registeredService = new ConcurrentHashSet<>();
    }

    @Override
    public <T> void addService(T service, String serviceName) {
        if(registeredService.contains(serviceName)) {
            return;
        }
        registeredService.add(serviceName);
        serviceMap.put(serviceName, service);
    }

    @Override
    public Object getService(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if(service == null) {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return service;
    }
}
